package com.sun2.booksotong.action.user;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.sun2.booksotong.service.user.Service4User;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {

	@Autowired
	private Service4User service4User;

	public static final String LOGIN_MESSAGE = "com.sun2.booksotong.action.user.LoginAction.message";
	
	public static final String LOGIN_NUM = "com.sun2.booksotong.action.user.LoginAction.num";

	private String account;
	
	private String password;
	
	private String message;

	@Override
	public String execute() throws Exception {
		HttpSession httpSession = ServletActionContext.getRequest().getSession();
		message = String.valueOf(httpSession.getAttribute(LOGIN_MESSAGE));
		if (message != null && !message.equals("")) {
			httpSession.setAttribute(LOGIN_MESSAGE, "");
			return ERROR;
		}
		Integer num = (Integer) (httpSession.getAttribute(LOGIN_NUM));
		if (num != null) {
			return SUCCESS;
		}
		if (account == null || account.equals("")) {
			return INPUT;
		} else {
			try {
				num = service4User.login(account, password);
				httpSession.setAttribute("USER_NUM", new Integer(num));
				return SUCCESS;
			} catch (Exception e) {
				message = (e.getCause() == null) ? e.getLocalizedMessage() : e.getCause().getMessage();
				return ERROR;
			}
		}
	}
	
	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}
